package com.gamejelly.proxy.handler;

import com.gamejelly.proxy.serialize.ProtostuffUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import org.springframework.core.ResolvableType;

import java.util.List;


/**
 * Created by haoyifen on 2017/6/16 21:27.
 */


public abstract class RpcCodec<T> extends ByteToMessageCodec<T> {
    private final Class<T> aClass;

    public RpcCodec() {
        ResolvableType resolvableType = ResolvableType.forInstance(this);
        ResolvableType genericType = resolvableType.getSuperType().getGeneric(0);
        Class<?> rawClass = genericType.getRawClass();
        aClass = (Class<T>) rawClass;
    }


    public Class<T> getaClass() {
        return aClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readableLength = in.readableBytes();
        byte[] bytes = new byte[readableLength];
        in.readBytes(bytes);
        T object = ProtostuffUtils.deserialize(bytes, aClass);
        out.add(object);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception {
        byte[] bytes = ProtostuffUtils.serialize(msg);
        out.writeBytes(bytes);
    }


}

